package fun.hijklmn.magic.common.utils;

import fun.hijklmn.magic.common.exception.MagicBizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.SecureRandom;

/**
 * @Description
 * @Author fs
 * @Date 2021/7/15 16:51
 * @Version 0.0.1-SNAPSHOT
 **/
public class AesSecurityUtil {

    private static final Logger logger = LoggerFactory.getLogger(AesSecurityUtil.class);

    public static String decrypt(String key, String content) {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(secureRandom);

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, generator.generateKey());
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] c = decoder.decodeBuffer(content);
            byte[] result = cipher.doFinal(c);
            String plainText = new String(result, "UTF-8");
            return plainText;
        } catch (Exception e) {
            logger.error("----------->解密失败", e);
            throw new MagicBizException("解密失败");
        }
    }

    public static String encrypt(String key, String content) {
        try {

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(secureRandom);

            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, generator.generateKey());
            byte[] p = content.getBytes("UTF-8");
            byte[] result = cipher.doFinal(p);
            BASE64Encoder encoder = new BASE64Encoder();
            String encoded = encoder.encode(result);
            return encoded;
        } catch (Exception e) {
            logger.error("----------->加密失败", e);
            throw new MagicBizException("加密失败");
        }
    }

}
